#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

#define Public "server"
#define Quit "quit\n"

void creat_fifo(char *name);
void server_send_data(void);
void client_rcv(void);
void client_send(void);

struct packet
{
	char name[20];
	char data[100];
};

struct packet client_packet,server_packet;
int client_num;
char client_mumber[5][20];


void creat_fifo(char *name)
{
	int fd;
	if((fd=open(name,O_RDONLY))==-1)
	{
		umask(0);
		mkfifo(name,S_IFIFO|0666);
	}
	else
	{
		close(fd);
	}
}

void server_send_data(void)
{
	int flag=0;
	int fd_public,fd_private;
	char target[20];
	char server_data[100];
	if((read(fd_public,&server_packet,sizeof(struct packet)))<=0)
	{
		printf("server receive failed\n");
		exit(1);
	}
	for(int x=0;x<client_num;x++)
	{
		if((strcmp(server_packet.name,client_mumber[x]))==0)
			flag=1;
	}
	if(flag==1)
	{
		strcpy(client_mumber[client_num],server_packet.name);
		client_num++;
	}
	if((strcmp(server_packet.data,Quit))==0)
	{
		sprintf(server_packet.data,"%s quit",server_packet.name);
		client_num--;
	}
	if(strncmp(server_packet.data,"to",2)==0)
	{
		int i=0,j=3;
		strcpy(server_data,server_packet.data);
		while(server_data[j] != ' ')
		{
			target[i]=server_data[j];
			i++;
			j++;
		}
		if((fd_private=open(target,O_WRONLY))>0)
		{
			if((write(fd_private,&server_packet,sizeof(struct packet)))<=0)
			{
				printf("server private send failed\n");
				exit(1);
			}
		}
	}
	else
	{
		for(int j=0;j<client_num;j++)
		{
			if(fd_private=open(client_mumber[j],O_WRONLY)>0)
			{
				if((write(fd_private,&server_packet,sizeof(struct packet)))<=0)
				{
					printf("server public send failed\n");
					exit(1);
				}
			}
		}
	}
}

void client_rcv()
{
	int fd_private;
	if((fd_private=open(client_packet.name,O_RDONLY))>0)
	{
		if((read(fd_private,&client_packet,sizeof(struct packet)))>0)
		{
			printf("%s:%s",client_packet.name,client_packet.data);
			close(fd_private);
		}
	}
	else
	{
		printf("failed open the fifo\n");
		exit(1);
	}
}

void client_send()
{
	int fd_public;

	if((fd_public=open(Public,O_WRONLY))>0)
	{
		if((write(fd_public,&client_packet,sizeof(struct packet)))>0)
		{
			close(fd_public);
		}
		else
		{
			printf("failed to write \n");
		}
		if((strcmp(client_packet.data,Quit))==0)
		{
			printf("quit\n");
			exit(0);
		}
	}
	else
	{
		printf("public fifo open failed\n");
		exit(1);
	}
}


